import { ListStore } from '@/store';
import { INITIAL_FORM_QUERY_VALUE, LIST_NAME, LOAD_CELLULAR_AREA_LIST_REQUEST_TASK_NAME } from '@/views/cellular-area-config/constants';
import { listCellularAreaConfig, exportCellularStoreApi, getChinaRegionUrlApi } from './api';
import { export_json_to_excel, formatJson } from '@/utils/vendor/Export2Excel';
import { Notification } from 'element-ui';
import { formatDate } from '@/utils/util';
import { TOP_CHANNELS, REGION_CITY_STORAGE_KEY } from '@/constants';
import { errorHandler, setLocalStorageByExpire, getLocalStorageByExpire } from '@/utils';

export default class Store extends ListStore {
  formQueryValue = { ...INITIAL_FORM_QUERY_VALUE };

  querying = false;

  visible = false;

  exporting = false;

  importVisible = false;

  importCompeteVisible = false;

  isModifyInfoVisible = false; // 修改蜂窝信息模态框

  exportLoading = false;
  cellularRowData = {};

  cityList = []; // 省市区列表

  // 加载省市列表
  loadRegionCitys = async () => {
    const storageData = getLocalStorageByExpire(REGION_CITY_STORAGE_KEY);
    if (storageData && Object.prototype.toString.call(storageData) === '[object Array]' && storageData.length > 0) {
      this.cityList = storageData;
      return;
    }

    try {
      const result = (await getChinaRegionUrlApi()) || [];
      const citys = result.map(item => {
        return {
          label: item.region_name,
          value: item.region_name,
          children:
            item.children?.map(childItem => {
              return {
                label: childItem.region_name,
                value: childItem.region_name,
                children:
                  childItem.children?.map(childChildItem => {
                    return {
                      label: childChildItem.region_name,
                      value: childChildItem.region_name,
                      children: undefined,
                    };
                  }) || undefined,
              };
            }) || undefined,
        };
      });

      if (citys.length > 0) {
        // 设置7天有效期
        setLocalStorageByExpire(REGION_CITY_STORAGE_KEY, citys);
        this.cityList = citys;
      } else {
        this.cityList = [];
      }
    } catch (error) {
      errorHandler({ error, showErrorNotification: false });
      this.cityList = [];
    }
  };

  // 加载列表
  loadCellularAreaConfigList = async ({ loadAction = 'reset', pageSize: inputPageSize, pageNum: inputPageNum } = {}) => {
    await this.loadList({
      requestTaskName: LOAD_CELLULAR_AREA_LIST_REQUEST_TASK_NAME,
      listName: LIST_NAME,
      loadAction,
      pageSize: inputPageSize,
      pageNum: inputPageNum,
      loadDataFunc: async ({ pageSize, pageNum }) => {
        const result = await listCellularAreaConfig(this.formQueryValue, { pageSize, pageNum });
        let { rows: data = [], total = 0 } = result || {};
        data = data.map(item => ({
          ...item,
        }));
        return { data, total };
      },
    });
  };

  // 查询蜂窝区域设置
  queryCellularAreaConfiguration = value => {
    this.formQueryValue = value;
    this.loadCellularAreaConfigList({ loadAction: 'pageNumChange', pageNum: 1 });
  };

  // 当前页变更
  pageNumChange = pageNum => {
    this.loadCellularAreaConfigList({ loadAction: 'pageNumChange', pageNum });
  };

  // 每页条数变更
  pageSizeChange = pageSize => {
    this.loadCellularAreaConfigList({ loadAction: 'pageSizeChange', pageSize });
  };

  resetTable = () => {
    this.loadCellularAreaConfigList({ loadAction: 'reset' });
  };
  //打开导入对话框
  onOpenImportModal = () => {
    this.importVisible = true;
  };
  //关闭导入对话框
  onCloseImport = () => {
    this.importVisible = false;
  };

  //打开导入对话框
  onOpenImportCompeteModal = () => {
    this.importCompeteVisible = true;
  };

  //关闭导入对话框
  onCloseImportCompete = () => {
    this.importCompeteVisible = false;
  };

  //导出蜂窝信息
  exportCellularInfo = async () => {
    try {
      console.log(this.formQueryValue);
      this.exporting = true;
      const total = this.list.table.total;
      const result = await listCellularAreaConfig(this.formQueryValue, { pageSize: total, pageNum: 1, countSql: false });
      const list = result.rows;
      if (list && list.length > 0) {
        const tHeader = [
          '顶级渠道',
          '城市',
          '分公司',
          '蜂窝',
          '蜂窝编码',
          '蜂窝益丰门店数',
          '竞对门店数',
          '蜂窝市占率%',
          '蜂窝类型',
          '蜂窝容量',
          '调价优先级',
          '创建人',
          '创建时间',
          '自动调价',
        ];
        const filterVal = [
          'topChannelCode',
          'city',
          'company',
          'cellularName',
          'cellularCode',
          'cellularStoreNum',
          'competeStoreNum',
          'marketRate',
          'cellularClassify',
          'capacityLevel',
          'cellularPriority',
          'creator',
          'createTime',
          'autoPrice',
        ];
        list.forEach(item => {
          item.createTime = formatDate(new Date(item.createTime), 'yyyy-MM-dd hh:mm:ss');
          item.topChannelCode = TOP_CHANNELS.find(i => i.id === item.topChannelCode)?.name;
          item.marketRate = item.marketRate ? Number(item.marketRate * 100).toFixed(3) + '%' : '';
          item.autoPrice = item.autoPrice === 'Y' ? '是' : '否';
        });
        const data = formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, '蜂窝信息');
      } else {
        Notification({
          title: '提示',
          message: `没有可导出的数据`,
          type: 'warning',
        });
      }
      this.exporting = false;
    } catch (e) {
      this.exporting = false;
      Notification({
        title: '提示',
        message: `导出列表异常`,
        type: 'error',
      });
    }
  };

  // 导出蜂窝及门店信息
  exportCellularAndStoreInfo = async () => {
    console.log('this.formQueryValue', this.formQueryValue);
    try {
      this.exportLoading = true;
      const res = (await exportCellularStoreApi(this.formQueryValue)) || null;
      if (!res) {
        this.exportLoading = false;
        Notification({ title: '提示', type: 'success', message: '数据生成成功! 请打开任务列表页面获取数据' });
      }
    } catch (error) {
      this.exportLoading = false;
      errorHandler({ error });
    }
  };

  // 初始加载数据
  init = async () => {
    await this.loadCellularAreaConfigList({ loadAction: 'reset' });
  };

  // 修改蜂窝信息
  openModifyModal = value => {
    this.cellularRowData = { ...value };
    this.isModifyInfoVisible = true;
  };

  onComfirmModifyModal = () => {
    this.init();
  };

  onDelete = () => {
    this.init();
  };
  onCloseModifyModal() {
    this.isModifyInfoVisible = false;
  }
}
